<template>
  <div class="recharge-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1>账户充值</h1>
        <p>为您的商户账户充值，确保业务正常运行</p>
      </div>
    </div>

    <!-- 当前余额 -->
    <el-card class="balance-card" shadow="never">
      <div class="balance-info">
        <div class="balance-icon">
          <el-icon size="40"><Wallet /></el-icon>
        </div>
        <div class="balance-details">
          <div class="balance-label">当前账户余额</div>
          <div class="balance-amount">¥{{ accountBalance.toFixed(2) }}</div>
          <div class="balance-tips">余额可用于推广费用、服务费等</div>
        </div>
      </div>
    </el-card>

    <!-- 充值表单 -->
    <el-card class="recharge-form-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>充值信息</span>
        </div>
      </template>

      <el-form
        ref="rechargeFormRef"
        :model="rechargeForm"
        :rules="rechargeRules"
        label-width="120px"
        class="recharge-form"
      >
        <!-- 充值方式选择 -->
        <el-form-item label="充值方式" prop="amountType">
          <el-radio-group v-model="rechargeForm.amountType">
            <el-radio label="quick">快速选择</el-radio>
            <el-radio label="custom">自定义金额</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 快速金额选择 -->
        <el-form-item v-if="rechargeForm.amountType === 'quick'" label="选择金额">
          <div class="quick-amounts">
            <div
              v-for="amount in quickAmounts"
              :key="amount"
              class="amount-option"
              :class="{ active: rechargeForm.amount === amount }"
              @click="rechargeForm.amount = amount"
            >
              <div class="amount-value">¥{{ amount }}</div>
              <div class="amount-desc" v-if="getAmountDesc(amount)">{{ getAmountDesc(amount) }}</div>
            </div>
          </div>
        </el-form-item>

        <!-- 自定义金额 -->
        <el-form-item v-if="rechargeForm.amountType === 'custom'" label="充值金额" prop="amount">
          <el-input-number
            v-model="rechargeForm.amount"
            :min="1"
            :max="50000"
            :precision="2"
            controls-position="right"
            style="width: 300px;"
            placeholder="请输入充值金额"
          />
          <span class="unit">元</span>
          <div class="amount-tips">
            <p>• 最低充值金额：¥1</p>
            <p>• 最高充值金额：¥50,000</p>
            <p>• 支持小数点后两位</p>
          </div>
        </el-form-item>

        <!-- 支付方式 -->
        <el-form-item label="支付方式" prop="paymentMethod">
          <div class="payment-methods">
            <div
              v-for="method in paymentMethods"
              :key="method.value"
              class="payment-option"
              :class="{ active: rechargeForm.paymentMethod === method.value }"
              @click="rechargeForm.paymentMethod = method.value"
            >
              <div class="payment-icon">
                <el-icon size="24"><component :is="method.icon" /></el-icon>
              </div>
              <div class="payment-info">
                <div class="payment-name">{{ method.name }}</div>
                <div class="payment-desc">{{ method.desc }}</div>
              </div>
              <div class="payment-check">
                <el-icon v-if="rechargeForm.paymentMethod === method.value" color="#409EFF">
                  <Check />
                </el-icon>
              </div>
            </div>
          </div>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="rechargeForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入充值备注（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 充值摘要 -->
    <el-card class="summary-card" shadow="never" v-if="!paymentInfo">
      <template #header>
        <div class="card-header">
          <span>充值摘要</span>
        </div>
      </template>

      <div class="summary-content">
        <div class="summary-item">
          <span class="label">充值金额：</span>
          <span class="value">¥{{ rechargeForm.amount.toFixed(2) }}</span>
        </div>
        <div class="summary-item">
          <span class="label">支付方式：</span>
          <span class="value">{{ getPaymentMethodName(rechargeForm.paymentMethod) }}</span>
        </div>
        <div class="summary-item">
          <span class="label">充值后余额：</span>
          <span class="value highlight">¥{{ (accountBalance + rechargeForm.amount).toFixed(2) }}</span>
        </div>
      </div>

      <div class="summary-actions">
        <el-button size="large" @click="goBack">返回</el-button>
        <el-button
          type="primary"
          size="large"
          :loading="rechargeProcessing"
          :disabled="rechargeForm.amount < 1"
          @click="processRecharge"
        >
          确认充值
        </el-button>
      </div>
    </el-card>

    <!-- 支付信息 -->
    <el-card class="payment-card" shadow="never" v-if="paymentInfo">
      <template #header>
        <div class="card-header">
          <span>完成支付</span>
          <div class="payment-timer">
            <el-icon><Timer /></el-icon>
            <span>{{ formatTime(remainingTime) }}</span>
          </div>
        </div>
      </template>

      <div class="payment-content">
        <!-- 支付宝支付 -->
        <div v-if="paymentInfo.type === 'alipay'" class="alipay-payment">
          <div class="payment-header">
            <el-icon size="32" color="#1677ff"><Money /></el-icon>
            <h3>支付宝支付</h3>
            <p>订单金额：¥{{ currentOrder.amount }}</p>
          </div>

          <div class="qr-code-section">
            <div class="qr-code">
              <img :src="generateQRCode(paymentInfo.qrCode)" alt="支付宝二维码" />
            </div>
            <div class="qr-instructions">
              <p v-for="instruction in paymentInfo.instructions" :key="instruction">
                {{ instruction }}
              </p>
            </div>
          </div>

          <div class="payment-actions">
            <el-button @click="openAlipay">打开支付宝支付</el-button>
          </div>
          <div class="payment-notice">
            <p>支付完成后系统将自动确认到账，请勿关闭此页面</p>
          </div>
        </div>

        <!-- 微信支付 -->
        <div v-if="paymentInfo.type === 'wechat'" class="wechat-payment">
          <div class="payment-header">
            <el-icon size="32" color="#07c160"><ChatDotRound /></el-icon>
            <h3>微信支付</h3>
            <p>订单金额：¥{{ currentOrder.amount }}</p>
          </div>

          <div class="qr-code-section">
            <div class="qr-code">
              <img :src="generateQRCode(paymentInfo.qrCode)" alt="微信支付二维码" />
            </div>
            <div class="qr-instructions">
              <p v-for="instruction in paymentInfo.instructions" :key="instruction">
                {{ instruction }}
              </p>
            </div>
          </div>

          <div class="payment-actions">
            <el-button @click="openWechat">打开微信支付</el-button>
          </div>
          <div class="payment-notice">
            <p>支付完成后系统将自动确认到账，请勿关闭此页面</p>
          </div>
        </div>

        <!-- 银行卡支付 -->
        <div v-if="paymentInfo.type === 'bank'" class="bank-payment">
          <div class="payment-header">
            <el-icon size="32" color="#f56c6c"><CreditCard /></el-icon>
            <h3>银行卡支付</h3>
            <p>订单金额：¥{{ currentOrder.amount }}</p>
          </div>

          <div class="bank-list">
            <div class="bank-instructions">
              <p v-for="instruction in paymentInfo.instructions" :key="instruction">
                {{ instruction }}
              </p>
            </div>

            <div class="banks">
              <div
                v-for="bank in paymentInfo.bankList"
                :key="bank.code"
                class="bank-item"
                @click="selectBank(bank)"
              >
                <div class="bank-icon">{{ bank.name.charAt(0) }}</div>
                <div class="bank-name">{{ bank.name }}</div>
              </div>
            </div>
          </div>

          <div class="payment-actions">
            <el-button type="primary" size="large" @click="openBankPay">
              前往银行支付页面
            </el-button>
          </div>
        </div>

        <!-- 支付状态检查 -->
        <div class="payment-status" v-if="checkingPayment">
          <el-icon class="is-loading"><Loading /></el-icon>
          <p>正在确认支付状态...</p>
        </div>
      </div>

      <div class="payment-footer">
        <el-button @click="cancelPayment">取消支付</el-button>
        <el-button type="text" @click="refreshPaymentStatus">刷新状态</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Wallet,
  Check,
  ChatDotRound,
  CreditCard,
  Money,
  Timer,
  Loading
} from '@element-plus/icons-vue'
import {
  getAccountBalance,
  rechargeAccount
} from '@/api/business'

const router = useRouter()

// 账户余额
const accountBalance = ref(0)

// 充值处理状态
const rechargeProcessing = ref(false)

// 支付相关状态
const paymentInfo = ref(null)
const currentOrder = ref(null)
const checkingPayment = ref(false)
const remainingTime = ref(0)
const paymentTimer = ref(null)

// 快速金额选项
const quickAmounts = [100, 200, 500, 1000, 2000, 5000]

// 支付方式选项
const paymentMethods = [
  {
    value: 'wechat',
    name: '微信支付',
    desc: '使用微信扫码支付',
    icon: 'ChatDotRound'
  },
  {
    value: 'alipay',
    name: '支付宝',
    desc: '使用支付宝扫码支付',
    icon: 'Money'
  },
  {
    value: 'bank',
    name: '银行卡',
    desc: '使用银行卡在线支付',
    icon: 'CreditCard'
  }
]

// 充值表单
const rechargeForm = reactive({
  amount: 100,
  amountType: 'quick',
  paymentMethod: 'wechat',
  remark: ''
})

// 表单验证规则
const rechargeRules = {
  amount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value < 1) {
          callback(new Error('充值金额不能少于1元'))
        } else if (value > 50000) {
          callback(new Error('单次充值金额不能超过50,000元'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
}

const rechargeFormRef = ref(null)

// 获取金额描述
const getAmountDesc = (amount) => {
  const descMap = {
    100: '适合小额推广',
    200: '日常使用',
    500: '推荐金额',
    1000: '月度预算',
    2000: '季度预算',
    5000: '年度预算'
  }
  return descMap[amount] || ''
}

// 获取支付方式名称
const getPaymentMethodName = (method) => {
  const methodMap = {
    wechat: '微信支付',
    alipay: '支付宝',
    bank: '银行卡'
  }
  return methodMap[method] || method
}

// 获取账户余额
const getAccountBalanceData = async () => {
  try {
    const response = await getAccountBalance()
    if (response.code === 200) {
      accountBalance.value = response.data.balance || 0
    }
  } catch (error) {
    console.error('获取账户余额失败:', error)
    accountBalance.value = 0
  }
}

// 处理充值
const processRecharge = async () => {
  try {
    await rechargeFormRef.value.validate()

    rechargeProcessing.value = true

    const response = await rechargeAccount({
      amount: rechargeForm.amount,
      paymentMethod: rechargeForm.paymentMethod,
      remark: rechargeForm.remark
    })

    if (response.code === 200) {
      // 保存订单和支付信息
      currentOrder.value = response.data
      paymentInfo.value = response.data.paymentInfo

      // 计算剩余时间
      const expireTime = new Date(response.data.expireTime).getTime()
      const now = new Date().getTime()
      remainingTime.value = Math.max(0, Math.floor((expireTime - now) / 1000))

      // 开始倒计时
      startPaymentTimer()

      ElMessage.success('充值订单创建成功，请完成支付')
      ElMessage.info('请在第三方支付平台完成支付，支付完成后点击"刷新状态"查看结果')
    } else {
      throw new Error(response.message || '创建充值订单失败')
    }
  } catch (error) {
    console.error('创建充值订单失败:', error)
    ElMessage.error(error.message || '创建充值订单失败，请重试')
  } finally {
    rechargeProcessing.value = false
  }
}

// 开始支付倒计时
const startPaymentTimer = () => {
  if (paymentTimer.value) {
    clearInterval(paymentTimer.value)
  }

  paymentTimer.value = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--
    } else {
      clearInterval(paymentTimer.value)
      ElMessage.warning('支付已超时，请重新发起充值')
      cancelPayment()
    }
  }, 1000)
}

// 格式化时间
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 生成二维码
const generateQRCode = (content) => {
  // 这里应该调用真实的二维码生成服务
  // 现在返回一个模拟的二维码图片
  return `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(content)}`
}

// 打开支付宝
const openAlipay = () => {
  if (paymentInfo.value?.payUrl) {
    window.open(paymentInfo.value.payUrl, '_blank')
  } else {
    ElMessage.error('支付链接无效')
  }
}

// 打开微信支付
const openWechat = () => {
  if (paymentInfo.value?.qrCode) {
    // 在移动端可以直接调用微信支付
    if (/MicroMessenger/i.test(navigator.userAgent)) {
      window.location.href = paymentInfo.value.qrCode
    } else {
      // 在PC端提示用户使用微信扫码
      ElMessage.info('请使用微信扫描二维码完成支付')
    }
  } else {
    ElMessage.error('微信支付链接无效')
  }
}

// 选择银行
const selectBank = (bank) => {
  ElMessage.info(`已选择${bank.name}`)
}

// 打开银行支付
const openBankPay = () => {
  if (paymentInfo.value?.payUrl) {
    window.open(paymentInfo.value.payUrl, '_blank')
  } else {
    ElMessage.error('银行支付链接无效')
  }
}

// 检查支付状态
const checkPaymentStatus = async () => {
  if (!currentOrder.value) {
    ElMessage.error('订单信息不存在')
    return
  }

  checkingPayment.value = true

  try {
    const response = await fetch(currentOrder.value.checkUrl)
    const result = await response.json()

    if (result.code === 200) {
      const status = result.data.status

      if (status === 'paid') {
        // 支付成功 - 进行二次验证
        clearInterval(paymentTimer.value)

        // 验证订单金额和时间
        const orderAmount = currentOrder.value.amount
        const orderTime = new Date(currentOrder.value.createTime).getTime()
        const now = new Date().getTime()

        // 检查订单是否在合理时间范围内（不能太快，防止虚假确认）
        if (now - orderTime < 10000) { // 10秒内完成支付可能是虚假的
          ElMessage.warning('支付确认过快，请稍后再试')
          checkingPayment.value = false
          return
        }

        // 刷新账户余额进行验证
        const oldBalance = accountBalance.value
        await getAccountBalanceData()
        const newBalance = accountBalance.value

        // 验证余额是否真实增加
        if (newBalance >= oldBalance + orderAmount) {
          ElMessage.success('支付成功！充值已到账')

          // 询问是否返回
          ElMessageBox.confirm('充值成功！是否返回营业管理页面？', '充值成功', {
            confirmButtonText: '返回',
            cancelButtonText: '继续充值',
            type: 'success'
          }).then(() => {
            router.push('/main/business')
          }).catch(() => {
            // 重置状态继续充值
            resetPaymentState()
          })
        } else {
          ElMessage.error('支付状态异常，余额未正确更新，请联系客服')
          cancelPayment()
        }
      } else if (status === 'failed') {
        // 支付失败
        ElMessage.error(`支付失败：${result.data.failReason || '未知原因'}`)
        cancelPayment()
      } else if (status === 'expired') {
        // 支付超时
        ElMessage.warning('支付已超时，请重新发起充值')
        cancelPayment()
      } else {
        // 仍在处理中
        ElMessage.info('支付处理中，请在第三方支付平台完成支付后再次刷新')
      }
    } else if (result.code === 404) {
      ElMessage.error('订单不存在或已失效')
      cancelPayment()
    } else {
      throw new Error(result.message || '查询支付状态失败')
    }
  } catch (error) {
    console.error('查询支付状态失败:', error)
    ElMessage.error('查询支付状态失败，请检查网络连接后重试')
  } finally {
    checkingPayment.value = false
  }
}

// 刷新支付状态
const refreshPaymentStatus = () => {
  checkPaymentStatus()
}

// 取消支付
const cancelPayment = () => {
  clearInterval(paymentTimer.value)
  resetPaymentState()
  ElMessage.info('已取消支付')
}

// 重置支付状态
const resetPaymentState = () => {
  paymentInfo.value = null
  currentOrder.value = null
  checkingPayment.value = false
  remainingTime.value = 0
  rechargeForm.amount = 100
  rechargeForm.amountType = 'quick'
  rechargeForm.remark = ''
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 页面初始化
onMounted(() => {
  getAccountBalanceData()
})
</script>

<style scoped>
.recharge-page {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.header-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.balance-card {
  margin-bottom: 20px;
}

.balance-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.balance-icon {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.balance-details {
  flex: 1;
}

.balance-label {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 4px;
}

.balance-amount {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.balance-tips {
  font-size: 12px;
  color: #9ca3af;
}

.recharge-form-card,
.summary-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: 600;
  color: #1f2937;
}

.quick-amounts {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 12px;
}

.amount-option {
  padding: 16px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  text-align: center;
}

.amount-option:hover {
  border-color: #d1d5db;
}

.amount-option.active {
  border-color: #3b82f6;
  background: #eff6ff;
}

.amount-value {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.amount-desc {
  font-size: 12px;
  color: #6b7280;
}

.unit {
  margin-left: 8px;
  color: #6b7280;
}

.amount-tips {
  margin-top: 8px;
  padding: 8px;
  background: #f8fafc;
  border-radius: 4px;
  font-size: 12px;
  color: #6b7280;
}

.amount-tips p {
  margin: 2px 0;
}

.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.payment-option {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.payment-option:hover {
  border-color: #d1d5db;
}

.payment-option.active {
  border-color: #3b82f6;
  background: #eff6ff;
}

.payment-icon {
  margin-right: 12px;
  color: #6b7280;
}

.payment-info {
  flex: 1;
}

.payment-name {
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 2px;
}

.payment-desc {
  font-size: 12px;
  color: #6b7280;
}

.payment-check {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.summary-content {
  margin-bottom: 24px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f3f4f6;
}

.summary-item:last-child {
  border-bottom: none;
}

.summary-item .label {
  color: #6b7280;
}

.summary-item .value {
  font-weight: 500;
  color: #1f2937;
}

.summary-item .value.highlight {
  color: #059669;
  font-size: 18px;
  font-weight: 600;
}

.summary-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.summary-actions .el-button {
  min-width: 100px;
}

/* 支付页面样式 */
.payment-card {
  margin-bottom: 20px;
}

.payment-timer {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #f56c6c;
  font-weight: 500;
}

.payment-content {
  padding: 20px 0;
}

.payment-header {
  text-align: center;
  margin-bottom: 30px;
}

.payment-header h3 {
  margin: 8px 0 4px 0;
  font-size: 20px;
  color: #1f2937;
}

.payment-header p {
  margin: 0;
  font-size: 16px;
  color: #6b7280;
}

.qr-code-section {
  display: flex;
  gap: 30px;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
}

.qr-code {
  text-align: center;
}

.qr-code img {
  width: 200px;
  height: 200px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.qr-instructions {
  flex: 1;
  max-width: 300px;
}

.qr-instructions p {
  margin: 8px 0;
  color: #6b7280;
  font-size: 14px;
  line-height: 1.5;
}

.payment-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-bottom: 20px;
}

.payment-notice {
  text-align: center;
  margin-top: 16px;
  padding: 12px;
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 6px;
}

.payment-notice p {
  margin: 0;
  color: #0369a1;
  font-size: 14px;
}

.bank-list {
  margin-bottom: 30px;
}

.bank-instructions {
  margin-bottom: 20px;
  text-align: center;
}

.bank-instructions p {
  margin: 4px 0;
  color: #6b7280;
  font-size: 14px;
}

.banks {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 12px;
  max-width: 600px;
  margin: 0 auto;
}

.bank-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.bank-item:hover {
  border-color: #3b82f6;
  background: #eff6ff;
}

.bank-icon {
  width: 40px;
  height: 40px;
  background: #f3f4f6;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  color: #374151;
  margin-bottom: 8px;
}

.bank-name {
  font-size: 14px;
  color: #1f2937;
  text-align: center;
}

.payment-status {
  text-align: center;
  padding: 40px 20px;
}

.payment-status .el-icon {
  font-size: 32px;
  color: #3b82f6;
  margin-bottom: 12px;
}

.payment-status p {
  margin: 0;
  color: #6b7280;
  font-size: 16px;
}

.payment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20px;
  border-top: 1px solid #f3f4f6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .qr-code-section {
    flex-direction: column;
    gap: 20px;
  }

  .qr-instructions {
    max-width: none;
    text-align: center;
  }

  .banks {
    grid-template-columns: repeat(2, 1fr);
  }

  .payment-actions {
    flex-direction: column;
  }

  .payment-footer {
    flex-direction: column;
    gap: 12px;
  }
}
</style>
